import { getCurrentUserId } from '../../../utils/user-helper.js';
import { checkAuthOnPageLoad } from '../../../utils/auth.js';
import { isTokenExpiredError, handleTokenExpiredError, checkAndHandleAuthError } from '../../../utils/auth-error-handler.js';

Page({
  data: {
    pageTitle: 'AI视频生成', // 默认标题
    formData: {
      content: '',
      speaker: '8b8180d5-97c3-44cb-bd1e-a756ab47c176', // 默认说话人ID
      sucaiId: 2631629 // 默认素材ID
    },
    speakerOptions: [
      { label: '标准女声', value: '8b8180d5-97c3-44cb-bd1e-a756ab47c176' },
      { label: '温柔女声', value: 'speaker-id-2' },
      { label: '活泼女声', value: 'speaker-id-3' },
      { label: '磁性男声', value: 'speaker-id-4' }
    ],
    sucaiOptions: [
      { label: '医疗科普', value: 2631629 },
      { label: '生活百科', value: 2631630 },
      { label: '科技资讯', value: 2631631 },
      { label: '教育培训', value: 2631632 }
    ],
    isSubmitting: false
  },

  onLoad(options) {
    // 检查登录状态，如果未登录则跳转到登录页
    if (!checkAuthOnPageLoad(this, options, true)) {
      return;
    }

    // 根据参数设置页面标题
    const titleMap = {
      'digital-human': 'AI数字人视频',
      'animation': 'AI动画视频',
      'common': 'AI视频生成',
      'commercial': 'AI商业视频',
      'education': 'AI教育视频'
    };
    
    const type = options.type || 'common';
    const title = titleMap[type] || 'AI视频生成';
    
    this.setData({
      pageTitle: title,
      taskType: type
    });

    // 动态设置导航栏标题
    wx.setNavigationBarTitle({
      title: title
    });
  },

  // 表单输入处理
  onContentChange(e) {
    this.setData({
      'formData.content': e.detail.value
    });
  },

  onSpeakerChange(e) {
    this.setData({
      'formData.speaker': e.detail.value
    });
  },

  onSucaiChange(e) {
    this.setData({
      'formData.sucaiId': e.detail.value
    });
  },



  // 表单验证
  validateForm() {
    const { content } = this.data.formData;
    
    if (!content.trim()) {
      wx.showToast({ title: '请输入视频内容', icon: 'error' });
      return false;
    }
    
    if (content.length < 10) {
      wx.showToast({ title: '视频内容至少10个字', icon: 'error' });
      return false;
    }
    
    return true;
  },

  // 提交任务
  async onSubmit() {
    if (!this.validateForm()) return;
    
    if (this.data.isSubmitting) return;
    
    this.setData({ isSubmitting: true });
    wx.showLoading({ title: '提交中...' });
    
    try {
      // 获取当前用户ID
      const userId = getCurrentUserId();
      if (!userId) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      const result = await wx.cloud.callFunction({
        name: 'video-task',
        data: {
          action: 'submit',
          userId: userId, // 传入用户ID
          data: {
            content: this.data.formData.content,
            speaker: this.data.formData.speaker,
            materialType: this.getMaterialTypeFromSucaiId(this.data.formData.sucaiId),
            taskType: this.data.taskType,
            digitalHuman: 'default' // 通用页面使用默认数字人
          }
        },
        timeout: 60000 // 设置60秒超时
      });
      
      // 检查是否为token过期错误
      if (checkAndHandleAuthError(result, {
        customMessage: '任务提交权限已过期，请重新登录'
      })) {
        wx.hideLoading();
        this.setData({ isSubmitting: false });
        return;
      }
      
      if (result.result.success) {
        wx.hideLoading();
        wx.showToast({ 
          title: '任务已提交', 
          icon: 'success',
          duration: 2000
        });
        
        // 使用setTimeout延迟显示modal，避免与toast冲突导致卡顿
        setTimeout(() => {
          wx.showModal({
            title: '提交成功',
            content: '视频生成任务已提交，正在后台处理中...\n\n预计需要1-3分钟完成，您可以在任务列表中查看处理进度',
            showCancel: true,
            cancelText: '继续创建',
            confirmText: '查看任务',
            success: (res) => {
              if (res.confirm) {
                // 先显示加载提示，然后再跳转
                wx.showLoading({
                  title: '跳转中...',
                  mask: true
                });
                
                                 // 使用setTimeout延迟跳转，让loading先显示
                 setTimeout(() => {
                   const taskId = result.result.data.taskId;
                   if (taskId) {
                     // 使用redirectTo避免页面栈过深，直接替换当前页面
                     wx.redirectTo({
                       url: `/packageTask/pages/task-detail/index?taskId=${taskId}&from=submit`,
                       success: () => {
                         wx.hideLoading();
                       },
                       fail: () => {
                         wx.hideLoading();
                         wx.showToast({
                           title: '跳转失败',
                           icon: 'none'
                         });
                       }
                     });
                   } else {
                     wx.switchTab({
                       url: '/pages/task-list/index',
                       success: () => {
                         wx.hideLoading();
                       },
                       fail: () => {
                         wx.hideLoading();
                         wx.showToast({
                           title: '跳转失败',
                           icon: 'none'
                         });
                       }
                     });
                   }
                 }, 100);
              }
            }
          });
        }, 500);
      } else {
        // 检查是否是积分不足的错误
        if (result.result.code === 403 && result.result.message && result.result.message.includes('积分不足')) {
          wx.hideLoading();
          wx.showModal({
            title: '积分不足',
            content: result.result.message + '\n\n每次提交任务需要消耗1积分\n您可以联系客服充值积分',
            showCancel: true,
            cancelText: '查看积分',
            confirmText: '联系客服',
            success: (res) => {
              if (res.confirm) {
                // 跳转到客服页面或显示客服联系方式
                wx.showToast({
                  title: '请通过设置页面联系客服',
                  icon: 'none',
                  duration: 2000
                });
              } else {
                // 跳转到积分页面
                wx.navigateTo({
                  url: '/packageUser/pages/points/index'
                });
              }
            }
          });
          return;
        }
        throw new Error(result.result.error || result.result.message || '提交失败');
      }
    } catch (error) {
      console.error('提交任务失败:', error);
      wx.hideLoading();
      wx.showToast({ 
        title: error.message || '提交失败', 
        icon: 'error' 
      });
    } finally {
      this.setData({ isSubmitting: false });
    }
  },

  // 预览效果
  onPreview() {
    if (!this.validateForm()) return;
    
    wx.showModal({
      title: '预览设置',
      content: `内容：${(this.data.formData.content || '').slice(0, 50)}...\n说话人：${this.getSpeakerLabel()}\n素材类型：${this.getSucaiLabel()}`,
      showCancel: false,
      confirmText: '确定'
    });
  },

  getSpeakerLabel() {
    const speaker = this.data.speakerOptions.find(item => item.value === this.data.formData.speaker);
    return speaker ? speaker.label : '';
  },

  getSucaiLabel() {
    const sucai = this.data.sucaiOptions.find(item => item.value === this.data.formData.sucaiId);
    return sucai ? sucai.label : '';
  },

  // 将素材ID转换为素材类型
  getMaterialTypeFromSucaiId(sucaiId) {
    const materialMap = {
      2631629: 'general',    // 医疗科普
      2631630: 'general',    // 生活百科
      2631631: 'general',    // 科技资讯
      2631632: 'education'   // 教育培训
    };
    return materialMap[sucaiId] || 'general';
  }
}); 